package com.javaear.zblog4java.system.controller.manager;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.javaear.generalmapper.GeneralMapper;
import com.javaear.zblog4java.system.component.AppConfig;
import com.javaear.zblog4java.system.entity.dto.ArticleDTO;
import com.javaear.zblog4java.system.entity.model.ArticleModel;
import com.javaear.zblog4java.system.entity.model.CategoryModel;
import com.javaear.zblog4java.system.entity.model.TagModel;
import com.javaear.zblog4java.system.entity.model.UserModel;
import com.javaear.zblog4java.system.util.RequestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author aooer
 */
@Controller
@RequestMapping("system/management")
public class ArticleManagerController {

    private static final String MNG_URL = "redirect:%s-management.html";
    private static final String EDT_URL = "system/edit/%s-edit";
    private static final String ADD_URL = "system/add/%s-add";

    @Autowired
    private GeneralMapper generalMapper;

    @RequestMapping("article-management")
    public void list(HttpServletRequest request, ModelMap modelMap) {
        int pageNo = 1;
        String pageNoStr = request.getParameter("pageNo");
        if (StringUtils.isNotBlank(pageNoStr) && StringUtils.isNumeric(pageNoStr))
            pageNo = Integer.parseInt(pageNoStr);
        if (pageNo < 1)
            pageNo = 1;
        ArticleModel serachModel = new ArticleModel();
        String searchCateId = request.getParameter("category");
        if (StringUtils.isNotBlank(searchCateId) && StringUtils.isNumeric(searchCateId))
            serachModel.setCateId(Integer.parseInt(searchCateId));
        String searchStatus = request.getParameter("status");
        if (StringUtils.isNotBlank(searchStatus) && StringUtils.isNumeric(searchStatus))
            serachModel.setStatus(Integer.parseInt(searchStatus));
        String searchTitle = request.getParameter("title");
        if (StringUtils.isNotBlank(searchTitle) && StringUtils.isNumeric(searchTitle))
            serachModel.setTitle(searchTitle);
        Page<ArticleModel> page = new Page<>(pageNo, (int) AppConfig.settingMap.get("App-systemPageSize"));
        modelMap.put("articles", generalMapper.selectPage(page, new EntityWrapper<>(serachModel)).stream().map(ArticleDTO::new).collect(Collectors.toList()));
        modelMap.put("page", page);
        modelMap.put("title", "文章管理");
    }


    @RequestMapping("article-add")
    public String add(HttpServletRequest request, ModelMap modelMap) {
        String type = request.getParameter("type");
        ArticleModel articleModel = RequestUtils.copyProperties(request, ArticleModel.class);
        if ((!StringUtils.isEmpty(type) && "show".equals(type)) || articleModel == null) {
            modelMap.put("title", "新建文章");
            return String.format(ADD_URL, "article");
        }
        try {
            articleModel.check();
        } catch (Exception e) {
            modelMap.put("title", "新建文章");
            return String.format(ADD_URL, "article");
        }
        //更新分类文章总数+1
        int cateArticleTotalCount = generalMapper.selectById(articleModel.getCateId(), CategoryModel.class).getCount();
        CategoryModel categoryModel = new CategoryModel();
        categoryModel.setId(articleModel.getCateId());
        categoryModel.setCount(cateArticleTotalCount + 1);
        generalMapper.updateSelectiveById(categoryModel);
        //更新用户文章总数
        int userArticleTotalCount = generalMapper.selectById(articleModel.getUserId(), UserModel.class).getArticles();
        UserModel userModel = new UserModel();
        userModel.setId(articleModel.getUserId());
        userModel.setArticles(userArticleTotalCount + 1);
        generalMapper.updateSelectiveById(userModel);
        //更新标签信息
        String tagStr = request.getParameter("tags");
        if (StringUtils.isNotBlank(tagStr)) {
            String[] tagArray = tagStr.split("、");
            Set<Integer> tagIdArray=new HashSet<>();
            for (String s : tagArray) {
                TagModel searchTagModel = new TagModel();
                searchTagModel.setName(s);
                TagModel resultTagModel = generalMapper.selectOne(searchTagModel);
                if (resultTagModel == null) {
                    searchTagModel.setCount(1);
                    generalMapper.insertSelective(searchTagModel);
                    tagIdArray.add(searchTagModel.getId());
                } else {
                    resultTagModel.setCount(resultTagModel.getCount() + 1);
                    generalMapper.updateSelectiveById(resultTagModel);
                    tagIdArray.add(resultTagModel.getId());
                }
            }
            articleModel.setTagIds(JSON.toJSONString(tagIdArray));
        }
        return String.format(generalMapper.insertSelective(articleModel) > 0 ? MNG_URL : ADD_URL, "article");
    }

    private Set<String> articleOldTags=new HashSet<>();
    @RequestMapping("article-edit")
    public String edit(HttpServletRequest request,ModelMap modelMap) {
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id))
            return String.format(MNG_URL, "article");
        String type = request.getParameter("type");
        ArticleModel articleModel = RequestUtils.copyProperties(request, ArticleModel.class);
        if ((StringUtils.isNotBlank(type) && "show".equals(type)) || articleModel == null) {
            ArticleModel articleModel1=generalMapper.selectById(Integer.parseInt(id), ArticleModel.class);
            request.setAttribute("model", articleModel1);
            if(StringUtils.isNotBlank(articleModel1.getTagIds())) {
                List<TagModel> tagModels = generalMapper.selectBatchIds(JSON.parseObject(articleModel1.getTagIds(), List.class), TagModel.class);
                articleOldTags.addAll(tagModels.stream().map(TagModel::getName).collect(Collectors.toList()));
                StringBuilder tags=new StringBuilder();
                tagModels.stream().forEach(tag->tags.append(tag.getName()).append("、"));
                request.setAttribute("tags",tags.substring(0,tags.toString().length()-1));
            }
            modelMap.put("title", "编辑文章");
            return String.format(EDT_URL, "article");
        }
        //更新标签信息
        String tagStr = request.getParameter("tags");
        if (StringUtils.isNotBlank(tagStr)) {
            String[] tagArray = tagStr.split("、");
            Set<Integer> tagIdArray=new HashSet<>();
            for (String tag : tagArray) {
                TagModel searchTagModel = new TagModel();
                searchTagModel.setName(tag);
                TagModel resultTagModel = generalMapper.selectOne(searchTagModel);
                if (resultTagModel == null) {
                    searchTagModel.setCount(1);
                    generalMapper.insertSelective(searchTagModel);
                    tagIdArray.add(searchTagModel.getId());
                } else {
                    if (!articleOldTags.contains(tag))
                        resultTagModel.setCount(resultTagModel.getCount() + 1);
                    generalMapper.updateSelectiveById(resultTagModel);
                    tagIdArray.add(resultTagModel.getId());
                }
            }
            articleModel.setTagIds(JSON.toJSONString(tagIdArray));
        }
        return String.format(generalMapper.updateSelectiveById(articleModel) > 0 ? MNG_URL : EDT_URL, "article");
    }

    @RequestMapping("article-remove")
    public String remove(HttpServletRequest request) {
        String id = request.getParameter("id");
        if (!org.springframework.util.StringUtils.isEmpty(id))
            generalMapper.deleteById(Integer.parseInt(id), ArticleModel.class);
        return String.format(MNG_URL, "article");
    }
}
